package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Grade;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.ResidueStudent;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.entity.views.ReNewDetailForTeacher;
import com.xmy.cultivate.entity.views.ResidueStatics;
import com.xmy.cultivate.mapper.RecordCourseMapper;
import com.xmy.cultivate.mapper.RenewDataMapper;
import com.xmy.cultivate.mapper.RepairCourseMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.service.impl.QuarterServiceImpl;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author min
 * @since 2022-11-29
 */
@RestController
@RequestMapping("/api/renewData")
@Api("续班表控制器")
public class RenewDataController {

    @Autowired
    IRenewDataService iRenewDataService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    RenewDataMapper renewDataMapper;

    @Autowired
    RepairCourseMapper repairCourseMapper;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IRenewClassService iRenewClassService;


    /**
     * 续班详情
     */
    @GetMapping("detailForTeacher")
    public Result detailForTeacher(@RequestParam Map reMap){

        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 20: Integer.valueOf((String)reMap.get("pageSize"));

        String yearPart = reMap.get("yearPart").toString();
        String subjectsId = reMap.get("subjectsId").toString();
        String quarterNum = reMap.get("quarterNum").toString();
        String teacherId = reMap.get("teacherId").toString();

        String isRenew = (String) reMap.get("isRenew");

        String gradeId = (String) reMap.get("gradeId");

        Map<String,Integer> nextQuarter = ConfigData.getNextQuarter(Integer.parseInt(yearPart),Integer.parseInt(quarterNum));

        QueryWrapper<ReNewDetailForTeacher> queryWrapper =  new QueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotBlank(yearPart),"year_part_renew",nextQuarter.get("yearPart"));
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum),"quarter_num_renew",nextQuarter.get("num"));
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);

        queryWrapper.eq("type",1);
        queryWrapper.eq("level",1);
        queryWrapper.isNotNull("year_class_id");
        //renewDataQueryWrapper.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
        if(quarterNum.equals(2)||quarterNum.equals(3)){
            queryWrapper.lt("year_class_id",9);
        }else {
            queryWrapper.le("year_class_id",9);
        }

        if(StringUtils.isNotBlank(gradeId)){
            queryWrapper.inSql("student_id","select student_id from student_grade as a where a.`status`=1 and a.reading_status not in(2,3) and grade_id = "+gradeId+"");
        }

        if(StringUtils.isNotBlank(isRenew)){
            queryWrapper.eq("is_renew",isRenew);
        }



        //queryWrapper.eq("arrive_affirm",2);
        queryWrapper.orderByDesc("created_at");

        IPage<IncomeDayReport> iPage = new Page<>(pageNum,pageSize);

        iRenewDataService.getRnewDetailForTeahcer(iPage,queryWrapper);

        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    /**
     *低于3次课
     * @param subjectsId
     * @param type
     * @param lessonType
     * @return
     */
    @GetMapping("/residueStudentCount")
    public Result residueStudentCount(@RequestParam("subjectsId") String subjectsId ,
                                      @RequestParam("type") Integer type,
                                      @RequestParam(value = "schoolId",required = false) String schoolId,
                                      @RequestParam(value = "yearClassId",required = false) String yearClassId,
                                      @RequestParam(value = "lessonType",required = false,defaultValue = "1") Integer lessonType){

        String startDate  = "";
        String endDate  = "";
        String trackId  = "";
        Integer quarterNum = 0;
        List<ResidueStatics> residueStatics = iRenewClassService.residueStudentCount(schoolId,subjectsId,type,quarterNum,startDate,endDate,trackId,lessonType,yearClassId);

        return new Result(Code.OK,residueStatics,"低于三次课人数统计完成~");
    }

    @PostMapping("residueDetailAll")
    @ApiOperation("学生全部明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type" , value = "类型" , required = true , dataType = "String"),
            @ApiImplicitParam(name = "teacherId" , value = "老师id" , required = false , dataType = "String"),
            @ApiImplicitParam(name = "schoolId" , value = "学校id" , required = false , dataType = "String"),
            @ApiImplicitParam(name = "whether" , value = "是否低于三次课" , required = true , dataType = "String"),
            @ApiImplicitParam(name = "gradeId" , value = "班级id" , required = false , dataType = "String")
    })
    public Result residueDetailAll(@RequestBody Map reMap,
                                   @RequestParam(value = "lessonType",required = false,defaultValue = "1") Integer lessonType){
        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 10: Integer.valueOf((String)reMap.get("pageSize"));
        String type = (String) reMap.get("type");
        String teacherId = (String) reMap.get("teacherId");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String whether = (String) reMap.get("whether");
        String gradeId = (String) reMap.get("gradeId");
        String yearClassId = (String) reMap.get("yearClassId");

        Quarter quarterNow = iQuarterService.getNowQuarter();
        IPage<ResidueStudent> iPage = new Page<>(pageNum,pageSize);

        iRenewClassService.residueStudentCountDetail(iPage,schoolId,subjectsId,quarterNow.getYearPart().toString(),quarterNow.getNum().toString(),gradeId,teacherId,type,Integer.parseInt(whether),lessonType,yearClassId);

        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()),"学生明细查询完成");
    }

    @PostMapping("residueDetail")
    @ApiOperation("学生科目明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type" , value = "类型" , required = true , dataType = "String"),
            @ApiImplicitParam(name = "teacherId" , value = "老师id" , required = false , dataType = "String"),
            @ApiImplicitParam(name = "schoolId" , value = "学校id" , required = false , dataType = "String"),
            @ApiImplicitParam(name = "subjectsId" , value = "科目id" , required = false, dataType = "String"),
            @ApiImplicitParam(name = "whether" , value = "是否低于三次课" , required = true , dataType = "String"),
            @ApiImplicitParam(name = "gradeId" , value = "班级id" , required = false , dataType = "String")
    })
    public Result residueDetail(@RequestBody Map reMap){
        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 10: Integer.valueOf((String)reMap.get("pageSize"));
        String type = (String) reMap.get("type");
        String teacherId = (String) reMap.get("teacherId");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String whether = (String) reMap.get("whether");
        List<String> gradeId = (List<String>) reMap.get("gradeId");

        Quarter quarterNow = iQuarterService.getNowQuarter();

        //分类型查找出符合条件的班级
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(type.equals("1")){
            queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);
        }else if(type.equals("2")){
            queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);
            queryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
        }else if(type.equals("3")){
            queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);
        }else if(type.equals("4")){
            queryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
        }
        queryWrapper.eq("year_part",quarterNow.getYearPart());
        queryWrapper.eq("status",1);
        List<String> gradeIdList = studentGradeMapper.ListGradeId(queryWrapper);

        //根据班级查找出班级对应的学生id列表
        QueryWrapper queryWrapperStudent = new QueryWrapper<>();
        queryWrapperStudent.in("grade_id",gradeIdList);
        queryWrapperStudent.in("grade_id",gradeId);
        queryWrapperStudent.eq("quarter_num",quarterNow.getNum());
        queryWrapperStudent.eq("reading_status",1);
        queryWrapperStudent.eq("year_part",quarterNow.getYearPart());
        List<String> studentIdList = studentGradeMapper.ListStudentId(queryWrapperStudent);

        //构造条件，查询出对应的订单列表
        QueryWrapper queryWrapperResidue = new QueryWrapper<>();
        queryWrapperResidue.eq("deleted",0);
        queryWrapperResidue.ne("status",2);
        queryWrapperResidue.eq("year_part",quarterNow.getYearPart());
        queryWrapperResidue.eq("quarter_num",quarterNow.getNum());
        queryWrapperResidue.eq("subjects_id",subjectsId);
        queryWrapperResidue.eq("reading_status",1);
        if(whether.equals("1")){
            queryWrapperResidue.gt("residue_course_count",0);
            queryWrapperResidue.le("residue_course_count",9);
        }else{
            queryWrapperResidue.gt("residue_course_count",9);
        }
        queryWrapperResidue.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapperResidue.in(studentIdList.size()!=0,"student_id",studentIdList);
        queryWrapperResidue.groupBy("student_id");

        List<ResidueStudent> residueStudents = new ArrayList<>();
        if(studentIdList.size() != 0){
            residueStudents =  renewDataMapper.residueStudent(queryWrapperResidue);
        }
        for(ResidueStudent residueStudent : residueStudents){
            QueryWrapper queryWrapperTeacher = new QueryWrapper<>();
            queryWrapperTeacher.eq("t1.year_part",quarterNow.getYearPart());
            queryWrapperTeacher.eq("t1.quarter_num",quarterNow.getNum());
            queryWrapperTeacher.eq("t1.reading_status",1);
            queryWrapperTeacher.eq("t1.subjects_id",subjectsId);
            queryWrapperTeacher.in("t1.grade_id",gradeId);
            queryWrapperTeacher.eq("t1.student_id",residueStudent.getStudentId());
            queryWrapperTeacher.groupBy("t2.teacher_id");
            teacherId = repairCourseMapper.getTeacherIdSubject(queryWrapperTeacher);
            queryWrapperTeacher.clear();
            residueStudent.setTeacherId(teacherId);
            residueStudent.setTeacherName(repairCourseMapper.getTeacherName(residueStudent.getTeacherId()));
            residueStudent.setSchoolName(recordCourseMapper.getSchoolName(residueStudent.getSchoolId()));
            residueStudent.setStudentName(recordCourseMapper.getStudentName(residueStudent.getStudentId()));
            String GradeId = studentGradeMapper.getGradeId(residueStudent.getStudentId());
            residueStudent.setGradeId(GradeId);
            residueStudent.setNianJi(CommonUtil.getYearClassNameForId(Integer.valueOf(renewDataMapper.getNianJi(GradeId))));
        }

        // 将 List<ResidueStudent> 转换为 IPage<ResidueStudent>
        Page<ResidueStudent> page = new Page<>(pageNum, pageSize, residueStudents.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if(pageSize * pageNum > residueStudents.size()){
            endPage  = residueStudents.size();
        }
        page.setRecords(residueStudents.subList(newPage,endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数
        return new Result(Code.OK,new PageResult(page.getRecords(),page.getTotal(),page.getPages()),"学生明细查询完成");
    }

    @GetMapping("gradeList")
    @ApiOperation("班级查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId" , value = "老师id" , required = false , dataType = "String"),
            @ApiImplicitParam(name = "schoolId" , value = "学校id" , required = false , dataType = "String"),
    })
    public Result gradeList(@RequestParam("teacherId") String teacherId,
                            @RequestParam("schoolId") String schoolId,
                            @RequestParam("subjectsId") String subjectsId,
                            @RequestParam("whether") String whether){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);

        Quarter quarterNow = iQuarterService.getNowQuarter();

        queryWrapper.eq("year_part",quarterNow.getYearPart());
        //queryWrapper.eq("quarter_num",quarterNow.getNum());
        queryWrapper.eq("status",1);
        List<Grade> gradeList = iGradeService.list(queryWrapper);
        QueryWrapper queryWrapperStudent = new QueryWrapper<>();
        QueryWrapper queryWrapperResidue = new QueryWrapper<>();
        for(Grade grade : gradeList){
            queryWrapperStudent.eq("grade_id",grade.getId());
            queryWrapperStudent.eq("quarter_num",quarterNow.getNum());
            queryWrapperStudent.eq("reading_status",1);
            queryWrapperStudent.eq("year_part",quarterNow.getYearPart());
            queryWrapperStudent.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            List<String> studentIdList = studentGradeMapper.ListStudentId(queryWrapperStudent);
            queryWrapperStudent.clear();
            queryWrapperResidue.eq("deleted",0);
            queryWrapperResidue.ne("status",2);
            queryWrapperResidue.eq("year_part",quarterNow.getYearPart());
            queryWrapperResidue.eq("quarter_num",quarterNow.getNum());
            queryWrapperResidue.eq("reading_status",1);
            if(whether.equals("1")){
                queryWrapperResidue.gt("residue_course_count",0);
                queryWrapperResidue.le("residue_course_count",9);
            }else{
                queryWrapperResidue.le("residue_course_count",9);
            }
            queryWrapperResidue.in(studentIdList.size()!=0,"student_id",studentIdList);
            queryWrapperResidue.groupBy("student_id");
            queryWrapperResidue.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            if(studentIdList.size() != 0){
                Integer sum = 0;
                List<Integer> integers = renewDataMapper.residueStudentCounts(queryWrapperResidue);
                for(Integer integer : integers){
                    sum += integer;
                }
                grade.setStudentCount(sum);
            }
            queryWrapperResidue.clear();
        }
        return new Result(Code.OK,gradeList,"班级查询完成");
    }
}